#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<time.h>
#include<sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>

#include<stdatomic.h>

#define LOOPS 10000
#define THREADS 200


struct spinlock {
    int locked;
};


void spin_lock(struct spinlock *lk){
    while(atomic_exchange(&(lk->locked), 1));
}
void spin_unlock(struct spinlock *lk){
    atomic_exchange(&(lk->locked), 0);
}

struct spinlock lk;
int global = 0;





void *inc(void *arg){
    for(int i=0; i<LOOPS; i++){
        spin_lock(&lk);
        global++;
        spin_unlock(&lk);    
    }
}


int main(){
    pthread_t tid[THREADS];
    int ret;

    
    for(int i=0; i<THREADS; i++){
        ret = pthread_create(&(tid[i]), NULL, inc, NULL);
        if(ret != 0){
            printf("thread create error\n");
            exit(1);
        }
    }
    for(int i=0; i<THREADS; i++){
        pthread_join(tid[i], NULL);
    }
    printf("global = %d\n", global);
    return 0;
}